﻿using Scriban;
using Scriban.Runtime;
using Scriban.Syntax;
using SqlSharp.Databases;

namespace SqlSharp.Infrastructure;

internal static class TemplateUtility
{
    public static void Render(FileInfo configFile, string outputPath, FileInfo templateFile, bool force)
    {
        var configuration = Configuration.FromJsonFile(configFile.FullName);
        var database = DatabaseProvider.Open(configuration);
        var template = Template.Parse(File.ReadAllText(templateFile.FullName));
        foreach (var table in database.Tables)
        {
            var scriptObject = new ScriptObject();
            scriptObject.Import("camelCase", GlobalFunctions.CamelCase);
            scriptObject.Import("pascalCase", GlobalFunctions.PascalCase);
            scriptObject.Import("typeMapper", new Func<string, string>(input =>
            {
                configuration.TypeMappings.TryGetValue(input.ToLower(), out var result);
                return result ?? string.Empty;
            }));
            var context = new TemplateContext();
            context.SetValue(ScriptVariable.Create("table", ScriptVariableScope.Global), table);
            context.PushGlobal(scriptObject);
            var content = template.Render(context);
            if (!Path.Exists(outputPath)) Directory.CreateDirectory(outputPath);
            var file = Path.Combine(outputPath, $"{GlobalFunctions.PascalCase(table.Name)}{templateFile.Extension}");
            if (!force && File.Exists(file)) throw new Exception($"The file '{file}' already exists.");
            File.WriteAllText(file, content);
        }
    }
}